"use strict";
import * as React from 'react';
const { View, ImageBackground, TouchableOpacity, ScrollView, StyleSheet, Image } = require('react-native');
const Geolocation = require('Geolocation');
const { connect } = require('react-redux');
import { SCREEN_WIDTH } from "../../constant";
const NavigationBar = require('react-native-navbar').default;
import { autoSize, commonProps, commonStyles } from "../../assets/styles/common";
import NavBackButton from "../../component/BackButton";
import MyImagePicker from "../../component/MyImagePicker";
import Colors from "../../assets/styles/Colors";
import MyText from "../../component/MyText";
import MyIcon from "../../component/icon";
import { toastValidateError } from "../../utils/tools";
const { Actions } = require("react-native-router-flux");
const { createForm } = require('rc-form');
const { List, InputItem, Picker, Button, TextareaItem } = require('antd-mobile');
let TextAreaStyle = require('antd-mobile/lib/textarea-item/style/index.native');
const newStyle = {};
for (const key in TextAreaStyle) {
    if (Object.prototype.hasOwnProperty.call(TextAreaStyle, key)) {
        newStyle[key] = Object.assign({}, StyleSheet.flatten(TextAreaStyle[key]));
        if (key === 'container') {
            newStyle[key].marginLeft = 0;
            newStyle[key].borderBottomWidth = 0;
            newStyle[key].borderBottomColor = 'transparent';
        }
    }
}
const paramsFields = [
    { field: 'business_license', error: '营业执照未选择' },
    { field: 'id_card', error: '申请人身份证选择' },
    { field: 'food_safety_license', error: '食品安全许可证未选择' },
    { field: 'store_img', error: '店铺图片未选择' },
    { field: 'id', error: '店铺id图片未填写' },
    { field: ['alipay', 'wx_user'], error: '提现渠道未填写', label: 'withDraw' },
];
class CreateShopPage extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.onMarkPickerChange = (e) => {
            this.props.form.setFieldsValue({ markets_id: e[0] });
            this.props.mark.list.map(item => {
                if (item.value == e[0]) {
                    this.setState({ selectedMarkName: item.label });
                }
            });
        };
        this.selectedHeaderImage = (key) => {
            const { params } = this.state;
            if (key === 'store_img') {
                this.imagePicker.options.pickerOptions.allowsEditing = true;
                this.imagePicker.showImagePicker().then(response => {
                    params[key] = {
                        uri: response['path'],
                        type: 'application/octet-stream',
                        name: response['fileName']
                    };
                    this.setState({ params });
                }).catch(e => {
                    console.log(e);
                });
            }
            else {
                this.imagePicker.options.pickerOptions.allowsEditing = false;
                this.imagePicker.showImagePicker().then(response => {
                    console.log(response);
                    params[key] = {
                        uri: response['uri'],
                        type: 'application/octet-stream',
                        name: response['fileName']
                    };
                    this.setState({ params });
                }).catch(e => {
                    console.log(e);
                });
            }
        };
        this.renderHeader = () => {
            return (<TouchableOpacity onPress={this.selectedHeaderImage.bind(this, 'store_img')}>
                <ImageBackground style={[commonStyles.centerVH, { width: SCREEN_WIDTH, height: SCREEN_WIDTH }]} source={this.state.params.store_img ? { uri: this.state.params.store_img.uri } : require('../../assets/image/background.png')}>

                </ImageBackground>
            </TouchableOpacity>);
        };
        this.getImagePickerItem = (name, key) => {
            return (<TouchableOpacity style={[commonStyles.flex1, commonStyles.centerVH]} onPress={this.selectedHeaderImage.bind(this, key)}>
                <MyText style={{ marginBottom: 10 }}>{name}</MyText>
                {this.state.params[key] ?
                <Image source={{ uri: this.state.params[key].uri }} style={{ width: 60, height: 60, backgroundColor: 'red' }}/> :
                <MyIcon name='icon-tianjia' size={60}/>}

            </TouchableOpacity>);
        };
        this.onInputItemChange = (l, e) => {
            const { params } = this.state;
            params[l] = e;
            this.setState({ params });
        };
        this.onCreate = () => {
            const { dispatch, form } = this.props;
            form.validateFields((error, value) => {
                if (!error) {
                    value.markets_id = value.markets_id[0];
                    if (this.checkParams()) {
                        const payload = Object.assign({}, value, this.state.params);
                        console.log(payload);
                        dispatch({
                            type: 'auth/createStore',
                            payload
                        });
                    }
                }
                else {
                    console.log(error);
                    toastValidateError(error);
                }
            });
        };
        this.checkParams = () => {
            const { params } = this.state;
            let errors = {};
            paramsFields.map((field) => {
                if (Array.isArray(field.field)) {
                    let err = true;
                    field.field.map(f => {
                        if (params[f]) {
                            err = false;
                        }
                    });
                    if (err) {
                        errors[field.label] = { errors: [{ message: field.error }] };
                    }
                }
                else {
                    if (!params[field.field]) {
                        errors[field.field] = { errors: [{ message: field.error }] };
                    }
                }
            });
            console.log(errors);
            if (Object.keys(errors).length > 0) {
                toastValidateError(errors);
                return false;
            }
            return true;
        };
        this.state = {
            errors: {
                phone: false,
                password: false,
                verifycode: false,
            },
            params: {},
            selectedMarkName: '请选择农贸市场'
        };
        this.imagePicker = new MyImagePicker();
        this.imagePicker.options.pickerOptions.allowsEditing = true;
        this.imagePicker.options.cropOptions.width = SCREEN_WIDTH;
        this.imagePicker.options.cropOptions.height = autoSize(SCREEN_WIDTH);
    }
    componentWillMount() {
        const { params } = this.state;
        params.id = this.props.auth.profile.id;
        this.setState({ params });
        Geolocation.getCurrentPosition(location => {
            params.gps = `${location.coords.longitude},${location.coords.latitude}`;
            this.props.form.setFieldsValue({ gps: `${location.coords.longitude},${location.coords.latitude}` });
        }, (err) => {
            alert(err.message);
        });
        this.props.dispatch({
            type: 'mark/fetchList',
        });
    }
    render() {
        const { getFieldProps } = this.props.form;
        return (<View style={commonStyles.container}>
                <NavigationBar {...commonProps.navBar} leftButton={<NavBackButton />} title={{ title: this.props.title, tintColor: '#fff' }}/>
                <ScrollView>
                    <List renderHeader={this.renderHeader}>

                        <InputItem {...getFieldProps('store_name', {
            initialValue: '',
            rules: [
                { required: true, message: '店铺名称未填写' },
            ]
        })} placeholder='输入店铺名称' clear labelNumber={4}>店铺名称</InputItem>

                        <InputItem {...getFieldProps('adder', {
            initialValue: '',
            rules: [
                { required: true, message: '店铺名称未填写' },
            ]
        })} placeholder='输入店铺地址' clear labelNumber={4}>{`地        址`}</InputItem>

                        <InputItem {...getFieldProps('store_phone', {
            rules: [
                { required: true, message: '铺联系方式未填写' },
            ],
            initialValue: this.props.auth.profile.store_phone
        })} placeholder='输入店铺联系方式' clear labelNumber={4}>{`电       话`}</InputItem>

                        <InputItem {...getFieldProps('gps', {
            rules: [
                { required: true, message: '店铺经纬度未填写' },
            ],
        })} placeholder='输入店铺经纬度(以英文逗号隔开)' clear labelNumber={4}>{`定       位`}</InputItem>

                        <Picker extra={this.state.selectedMarkName} data={this.props.mark.list} title="农贸市场" cols={1} {...getFieldProps('markets_id', {
            initialValue: [1],
            rules: [
                { required: true, message: '所属农贸市场未填写' },
            ],
        })} onChange={this.onMarkPickerChange}>
                            <List.Item arrow="horizontal">农贸市场</List.Item>
                        </Picker>
                        <View style={{ height: 10, backgroundColor: Colors.BgColor }}/>

                        <InputItem onChange={this.onInputItemChange.bind(this, 'alipay')} placeholder='输入支付宝账号' clear labelNumber={5}>支付宝账号</InputItem>

                        <InputItem onChange={this.onInputItemChange.bind(this, 'wx_user')} placeholder='输入微信账号' clear labelNumber={4}>微信账号</InputItem>

                        <View style={{ padding: 14 }}>
                            <MyText color={Colors.Black}>店铺介绍</MyText>
                            <View style={{ paddingHorizontal: 20 }}>
                                <View style={{
            borderWidth: 1,
            borderColor: '#d0d0d0',
            borderRadius: 10,
            padding: 5,
            marginTop: 10
        }}>
                                    <TextareaItem {...getFieldProps('description', {
            initialValue: '',
            rules: [
                { required: true, message: '店铺介绍未填写' },
            ],
        })} styles={StyleSheet.create(newStyle)} rows={5} count={100}/>
                                </View>
                            </View>
                        </View>

                        <View style={[commonStyles.flexRow]}>
                            {this.getImagePickerItem('营业执照', 'business_license')}
                            {this.getImagePickerItem('申请人身份证', 'id_card')}
                            {this.getImagePickerItem('食品安全许可证', 'food_safety_license')}
                        </View>
                        <View style={{ padding: 10 }}>
                            <Button type={'primary'} style={{ height: 35 }} loading={this.props.auth.loading} disabled={this.props.auth.loading} onClick={this.onCreate}>创建店铺</Button>
                        </View>
                    </List>
                </ScrollView>
            </View>);
    }
}
CreateShopPage.defaultProps = {
    title: '创建店铺'
};
const Wrapper = createForm()(CreateShopPage);
export default connect(({ auth, mark }) => ({ auth, mark }))(Wrapper);
